package com.layblog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.layblog.common.lang.Result;
import com.layblog.entity.User;
import com.layblog.mapper.UserMapper;
import com.layblog.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.layblog.shiro.AccountProfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 公众号：java思维导图
 * @since 2021-04-18
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Result register(User user) {
        if (StringUtils.isEmpty(user.getEmail()) || StringUtils.isEmpty(user.getPassword())
                || StringUtils.isEmpty(user.getUsername())) {
            return Result.fail("必要字段不能为空");
        }

        User po = this.getOne(new QueryWrapper<User>().eq("email", user.getEmail()).or().eq("username", user.getUsername()));
        if (po != null) {
            return Result.fail("邮箱或昵称已被注册");
        }

        String passMd5 = SecureUtil.md5(user.getPassword());

        po = new User();
        po.setEmail(user.getEmail());
        po.setPassword(passMd5);
        po.setCreated(new Date());
        po.setUsername(user.getUsername());
        po.setAvatar("/res/images/avatar/default.png");
        po.setPoint(0);
        po.setGender("0");
        po.setVipLevel(0);

        return this.save(po) ? Result.succ("") : Result.fail("注册失败");
    }

    @Override
    public AccountProfile login(String username, String password) {
        log.info("------------>进入用户登录判断，获取用户信息步骤");

        User user = this.getOne(new QueryWrapper<User>().eq("email", username));
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }

        if (!user.getPassword().equals(password)) {
            throw new IncorrectCredentialsException("密码错误");
        }

        //更新最后登录时间
        user.setLasted(new Date());
        this.updateById(user);

        AccountProfile profile = new AccountProfile();

        BeanUtil.copyProperties(user, profile);

        return profile;
    }
}
